Page({
  data: {
    serviceCategoryList: [],
    activeTab: 0,
    loading: false,
    categoryLoading: false,
    serviceLoading: false,
    categoryPage: 1,
    categoryPageSize: 10,
    hasMoreCategories: true,
    servicePageSize: 8,
    lastRefreshTime: ''
  },

  onLoad() {
    this.getCategoryList()
    // 获取当前时间作为最后刷新时间
    this.setData({
      lastRefreshTime: this.formatRefreshTime(new Date())
    })
  },

  // 页面显示时执行
  onShow() {
    // 检查是否有需要激活的分类ID
    const app = getApp()
    if (app.globalData && app.globalData.activeCategoryId) {
      // 获取激活分类ID
      const activeCategoryId = app.globalData.activeCategoryId
      // 清除全局变量，避免下次进入页面时仍然切换
      app.globalData.activeCategoryId = null

      // 查找分类ID对应的索引
      if (this.data.serviceCategoryList.length > 0) {
        const index = this.data.serviceCategoryList.findIndex(item => item.id === activeCategoryId)
        if (index !== -1 && index !== this.data.activeTab) {
          // 切换到对应分类
          this.setData({ activeTab: index })
          // 如果该分类尚未加载服务数据，则加载
          if (this.data.serviceCategoryList[index].services.length === 0) {
            this.getServiceListByCategory(index, true)
          }
        }
      }
    }
  },

  // 格式化刷新时间
  formatRefreshTime(date) {
    const hour = date.getHours().toString().padStart(2, '0')
    const minute = date.getMinutes().toString().padStart(2, '0')
    return `${hour}:${minute}`
  },

  // 获取分类列表
  getCategoryList() {
    this.setData({
      loading: true,
      categoryLoading: true
    })

    // 引入请求工具
    const { post } = require('../../utils/request')

    post('/api/category/list/page/vo', {
      current: this.data.categoryPage,
      pageSize: this.data.categoryPageSize
    }).then(res => {
      if (res.code === 0 && res.data) {
        const categoryList = (res.data.records || []).map(item => {
          // 处理图片为空的情况，使用默认图片
          return {
            ...item,
            image: item.image || '/assets/images/default.png',
            services: [], // 初始化服务列表为空
            current: 1,   // 每个分类的当前页码
            hasMore: true // 每个分类的是否有更多数据标记
          }
        })

        const mergedCategoryList = this.data.categoryPage === 1 ?
          categoryList :
          [...this.data.serviceCategoryList, ...categoryList];

        this.setData({
          serviceCategoryList: mergedCategoryList,
          hasMoreCategories: res.data.current < res.data.pages
        })

        // 获取第一个分类的服务列表
        if (categoryList.length > 0 && this.data.categoryPage === 1) {
          this.setData({ activeTab: 0 })
          this.getServiceListByCategory(0, true)
        }
      } else {
        wx.showToast({
          title: res.message || '获取分类列表失败',
          icon: 'none'
        })
      }
    }).catch(err => {
      console.error('获取分类列表失败', err)
      wx.showToast({
        title: '网络错误，请稍后重试',
        icon: 'none'
      })
    }).finally(() => {
      this.setData({
        categoryLoading: false,
        loading: this.data.serviceLoading // 只有当服务也加载完成时才完全结束加载状态
      })
    })
  },

  // 获取分类下的服务列表
  getServiceListByCategory(tabIndex, resetPage = false) {
    const { serviceCategoryList, activeTab } = this.data
    const tabIndexToUse = tabIndex !== undefined ? tabIndex : activeTab

    // 如果没有分类，则直接返回
    if (!serviceCategoryList[tabIndexToUse]) {
      return
    }

    const categoryId = serviceCategoryList[tabIndexToUse].id

    // 如果需要重置页码
    if (resetPage) {
      serviceCategoryList[tabIndexToUse].current = 1
      serviceCategoryList[tabIndexToUse].services = []
      this.setData({ serviceCategoryList })
    }

    // 当前分类的页码
    const current = serviceCategoryList[tabIndexToUse].current

    this.setData({
      loading: true,
      serviceLoading: true
    })

    const { post } = require('../../utils/request')

    // 使用listServicesVOByPage接口获取服务列表
    post('/api/services/list/page/vo', {
      categoryId: categoryId,
      current: current,
      pageSize: this.data.servicePageSize
    }).then(res => {
      if (res.code === 0 && res.data) {
        // 处理服务数据
        const serviceList = (res.data.records || []).map(item => {
          return {
            id: item.id,
            title: item.name,
            desc: item.description || '暂无描述',
            price: item.price,
            unit: item.unit || '次',
            imgUrl: item.image || '/assets/images/default.png',
            categoryName: item.categoryName,
            duration: item.duration || 0
          }
        })

        // 更新对应分类的服务列表
        const updatedCategoryList = [...serviceCategoryList]
        updatedCategoryList[tabIndexToUse].services = [
          ...updatedCategoryList[tabIndexToUse].services,
          ...serviceList
        ]

        // 更新是否有更多数据标记
        updatedCategoryList[tabIndexToUse].hasMore = serviceList.length >= this.data.servicePageSize
          && res.data.total > updatedCategoryList[tabIndexToUse].services.length

        this.setData({
          serviceCategoryList: updatedCategoryList
        })
      } else {
        wx.showToast({
          title: res.message || '获取服务列表失败',
          icon: 'none'
        })
      }
    }).catch(err => {
      console.error('获取服务列表失败', err)
      wx.showToast({
        title: '网络错误，请稍后重试',
        icon: 'none'
      })
    }).finally(() => {
      this.setData({
        serviceLoading: false,
        loading: this.data.categoryLoading // 只有当分类也加载完成时才完全结束加载状态
      })
    })
  },

  // 加载更多服务
  loadMoreServices() {
    const { activeTab, serviceCategoryList } = this.data

    if (serviceCategoryList[activeTab] &&
      serviceCategoryList[activeTab].hasMore &&
      !this.data.loading) {
      // 增加当前分类的页码
      const updatedCategoryList = [...serviceCategoryList]
      updatedCategoryList[activeTab].current++

      this.setData({
        serviceCategoryList: updatedCategoryList
      })

      // 加载更多服务
      this.getServiceListByCategory(activeTab)
    }
  },

  // 切换Tab
  changeTab(e) {
    const index = e.currentTarget.dataset.index
    this.setData({
      activeTab: index
    })

    // 获取当前分类的服务列表，如果为空才加载
    const { serviceCategoryList } = this.data
    if (serviceCategoryList[index].services.length === 0) {
      this.getServiceListByCategory(index, true)
    }
  },

  // 跳转到服务详情
  goToServiceDetail(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/service/detail/detail?id=${id}`
    })
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.setData({
      categoryPage: 1,
      lastRefreshTime: this.formatRefreshTime(new Date())
    })
    this.getCategoryList()
    wx.stopPullDownRefresh()
  },

  // 上拉加载更多
  onReachBottom() {
    this.loadMoreServices()
  },

  // 处理服务列表点击
  handleServiceTap(e) {
    const id = e.currentTarget.dataset.id
    this.goToServiceDetail({ currentTarget: { dataset: { id } } })
  }
}) 